package me.caofeng.handler;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import com.sun.org.apache.regexp.internal.RE;
import me.caofeng.enums.ResponseCode;
import me.caofeng.pojo.Response;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.sql.SQLException;

/**
 * Copyright © 2017曹峰. All rights reserved.
 *
 * @Prject: mall
 * @Package: me.caofeng.handler
 * @Description: 统一错误处理机制，避免向客户端输出500错误
 * @Author: 曹峰 blog.caofeng.me
 * @Date: 2017-06-22 15:38
 * @Version: V1.0
 */
@ControllerAdvice
public class AppWideExceptionHandler {
    private static Logger LOGGER = LogManager.getLogger(AppWideExceptionHandler.class);

    /**
     * @Author:曹峰 blog.caofeng.me
     * @Date: 2017/7/4 9:16
     * @Description: 统一处理参数转换错误
    */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public Response errorHandler(MethodArgumentTypeMismatchException e) {
        LOGGER.error(e);
        return Response.response(ResponseCode.ILLEGAL_ARGUMENT, "参数错误", null);
    }


    /**
     * @Author:曹峰 blog.caofeng.me
     * @Date: 2017/7/4 9:16
     * @Description: 统一处理sql语句错误
    */
    @ExceptionHandler(SQLException.class)
    @ResponseBody
    public Response sqlHandler(SQLException e) {
        LOGGER.error(e);
        return Response.response(ResponseCode.ERROR, "您触发了神秘按钮", null);
    }

}
